package com.yuhanginfo.modules.web.util;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.method.HandlerMethod;
import com.yuhanginfo.common.utils.Exceptions;
import com.yuhanginfo.common.utils.SpringContextHolder;
import com.yuhanginfo.common.utils.StringUtils;
import com.yuhanginfo.modules.web.dao.WebLogDao;
import com.yuhanginfo.modules.web.entity.WebLog;
import com.yuhanginfo.modules.web.entity.WebYongUser;

/**
 * 字典工具类
 * @author YuHangInfo
 * @version 2014-11-7
 */
public class LogUtils {
	
	private LogUtils(){}
	public static final String CACHE_MENU_NAME_PATH_MAP = "menuNamePathMap";
	
	private static WebLogDao logDao = SpringContextHolder.getBean(WebLogDao.class);
	
	/**
	 * 保存日志
	 */
	public static void saveLog(HttpServletRequest request, String title){
		saveLog(request, null, null, title);
	}
	
	/**
	 * 保存日志
	 */
	public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title){
		WebYongUser user = WebUserUtils.getYongUser();
		if (user != null && user.getId() != null){
			WebLog log = new WebLog();
			log.setTitle(title);
			log.setType(ex == null ? WebLog.TYPE_ACCESS : WebLog.TYPE_EXCEPTION);
			log.setRemoteAddr(StringUtils.getRemoteAddr(request));
			log.setUserAgent(request.getHeader("user-agent"));
			log.setRequestUri(request.getRequestURI());
			log.setParams(request.getParameterMap());
			log.setMethod(request.getMethod());
			// 异步保存日志
			new SaveLogThread(log, handler, ex).start();
		}
	}

	/**
	 * 保存日志线程
	 */
	public static class SaveLogThread extends Thread{
		
		private WebLog log;
		private Object handler;
		private Exception ex;
		
		public SaveLogThread(WebLog log, Object handler, Exception ex){
			super(SaveLogThread.class.getSimpleName());
			this.log = log;
			this.handler = handler;
			this.ex = ex;
		}
		
		@Override
		public void run() {
			// 获取日志标题
			if (StringUtils.isBlank(log.getTitle())){
				if (handler instanceof HandlerMethod){
					Method m = ((HandlerMethod)handler).getMethod();
					RequiresPermissions rp = m.getAnnotation(RequiresPermissions.class);
					@SuppressWarnings("unused")
					String permission = rp != null ? StringUtils.join(rp.value(), ",") : "";
				}
			}
			// 如果有异常，设置异常信息
			log.setException(Exceptions.getStackTraceAsString(ex));
			// 如果无标题并无异常日志，则不保存信息
			if (StringUtils.isBlank(log.getTitle()) && StringUtils.isBlank(log.getException())){
				return;
			}
			// 保存日志信息
			log.preInsert();
			logDao.insert(log);
		}
	}

	
}
